package com.example.wxCode.utils.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.Buffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;

/**
 * @Description 封装一下发送http请求相关操作
 * @Author zengzerui
 * @Date 2025/4/18
 */
@Slf4j
public class ApacheHttpUtil {
    /**
     * 使用Apache HttpClient发送GET请求
     * @param url   基础URL（不含参数）
     * @param param 请求参数Map
     * @return 响应内容字符串
     */
    public static String sendGet(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        try {
            // 1. 构建带参数的URL
            URIBuilder uriBuilder = new URIBuilder(url);
            if (param != null) {
                param.forEach(uriBuilder::addParameter); // 自动处理URL编码
            }
            URI uri = uriBuilder.build();
            log.info("GET请求地址: {}", uri);

            // 2. 创建HttpGet请求
            HttpGet httpGet = new HttpGet(uri);
            // 设置请求头
            httpGet.setHeader("accept", "*/*");
            httpGet.setHeader("connection", "Keep-Alive");
            httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0)");

            // 3. 执行请求
            response = httpClient.execute(httpGet);

            // 4. 打印响应头（调试用）
            Arrays.stream(response.getAllHeaders())
                    .forEach(header -> log.debug("{}: {}", header.getName(), header.getValue()));

            // 5. 获取响应体
            if (response.getEntity() != null) {
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常: ", e);
        } finally {
            // 6. 确保资源关闭
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                log.error("关闭HTTP连接时异常: ", e);
            }
        }
        return result;
    }

    /**
     * 使用Apache HttpClient发送GET请求
     * @param URL   基础URL（不含参数）
     * @param json 请求参数Map
     * @return 响应内容字符串
     */
    public static byte[] sendPost(String URL, String json) {
        String obj = null;
        InputStream inputStream = null;
        Buffer reader = null;
        byte[] data = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    inputStream = entity.getContent();
                    ByteArrayOutputStream byteArrayOutputStream = readInputStream(inputStream);
                    String entityStr = byteArrayOutputStream.toString();
                    if (isJson(entityStr)) {
                        log.info("WxacodeApiUtil Post, response entity = {}", entityStr);
                    } else {
                        data = byteArrayOutputStream.toByteArray();

                    }
                }
                return data;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }


    public static boolean isJson(String content) {
        try {
            JSONObject jsonStr = JSONObject.parseObject(content);
//            System.out.println(jsonStr);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 将流 保存为数据数组
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static ByteArrayOutputStream readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream;
    }

}
